package com.example.myapplication.coreutil

import android.Manifest
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.animation.LinearInterpolator
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapsInitializer
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CircleOptions
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.maps.model.PolylineOptions
import com.amap.api.maps.model.animation.RotateAnimation
import com.example.myapplication.R
import com.example.myapplication.data.WeatherData
import com.example.myapplication.data.WeatherResponse
import com.google.gson.Gson
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.Toaster
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import kotlin.random.Random

object CoreUtil {
    const val LOCATION_PERMISSION_REQUEST_CODE = 1001

    val pathCollection = mutableListOf<LatLng>()

    val handler = Handler(Looper.getMainLooper())

    val generateRandomPointInterval = 5000

    /**
     * 初始化土司的
     */
    fun initToaster(application: Application) {
        Toaster.init(application)
    }


    // 申请授权
    fun requestLocationPermission(activity: Activity) {
        val permissions = arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )

        ActivityCompat.requestPermissions(
            activity,
            permissions,
            LOCATION_PERMISSION_REQUEST_CODE
        )
    }

    // 定位授权
    fun isLocationPermissionGranted(activity: Activity): Boolean {
        return ContextCompat.checkSelfPermission(
            activity,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(
                    activity,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED
    }

    /**
     * usage: MainActivity() do
     *  CoreUtil.initPermission(this)
     */
    fun initPermission(context: Context) {
        XXPermissions.with(context)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .permission(Permission.READ_MEDIA_IMAGES)
            .permission(Permission.READ_MEDIA_AUDIO)
            .permission(Permission.READ_MEDIA_VIDEO)
//            .permission(Permission.ACCESS_BACKGROUND_LOCATION)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
//                        Toast.makeText(context, "获取部分权限成功", Toast.LENGTH_SHORT).show()
                        Toaster.show("获取部分权限成功")
                    } else {
//                        Toast.makeText(context, "全部定义权限获取成功", Toast.LENGTH_SHORT).show()
                        Toaster.show("获取全部定义权限成功")
                    }
                    return
                }
            })
    }

    /**
     * usage: MainActivity() do
     *  CoreUtil.initGaodePrivacy(this)
     */
    fun initGaodePrivacy(context: Context) {
        MapsInitializer.updatePrivacyShow(context, true, true)
        MapsInitializer.updatePrivacyAgree(context, true)
    }

    /**
     * 更新隐私设置
     *  CoreUtil.initClientPrivacy(
     *             context = this,
     *             isContains = true, // 隐私权政策包含高德隐私权政策
     *             isShow = true,    // 隐私权政策弹窗展示告知用户
     *             isAgree = true    // 用户同意隐私权政策
     *         )
     */
    // 设置隐私合规: https://lbs.amap.com/api/android-sdk/guide/create-project/dev-attention#t2
    // usage: 在MainActivity onCreate里面调用，在Client初始化之前调用
    fun initGaodeAllPrivacyFirst(
        context: Context,
        isContains: Boolean,
        isShow: Boolean,
        isAgree: Boolean
    ) {
        MapsInitializer.updatePrivacyShow(context, isContains, isShow)
        MapsInitializer.updatePrivacyAgree(context, isAgree)
        AMapLocationClient.updatePrivacyShow(context, isContains, isShow)
        AMapLocationClient.updatePrivacyAgree(context, isAgree)
    }

    /**
     * usage: 确定AMap不为空的情况下
     * CoreUtil.showMyLocationByAMap(amapinstance!!)
     * 注意这里自定义了一些style
     */
    fun showMyLocationByAMap(aMap: AMap) {
        var myLocationStyle: MyLocationStyle = MyLocationStyle()
        myLocationStyle.apply {
            interval(100000)
            // 永远显示在中间
//            myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW)
            // 这个蓝点图标不能过大
            myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.car))
        }

        aMap.apply {
            myLocationStyle = myLocationStyle
            showIndoorMap(true)
            mapType = AMap.MAP_TYPE_NIGHT
            isTrafficEnabled = true
            setMapLanguage("en")
            isMyLocationEnabled = true
        }
    }

    fun addMarkerOnAMap(aMap: AMap) {
        val latLng = LatLng(39.906901, 116.397972)
        val marker = aMap.addMarker(
            MarkerOptions()
                .position(latLng)
                .title("北京")
                .snippet("地道")
                .setFlat(true)
        )

        val anim = RotateAnimation(marker.rotateAngle, marker.rotateAngle + 180)
        val duration = 1000L
        with(marker) {
            anim.setDuration(duration)
            anim.setInterpolator(LinearInterpolator())
            setAnimation(anim)
            startAnimation()
        }
    }

    /**初始画定位客户端
     * usage: initLocationClient(ActivityInstance)
     */
    fun initLocationClient(context: Context) {
        val locationClient = AMapLocationClient(context)
        val locationOption = AMapLocationClientOption()
            .apply {
                locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
                isOnceLocation = false
                interval = 5000
            }
        locationClient.setLocationOption(locationOption)
        locationClient.setLocationListener { loc ->
            if (loc.errorCode == 0) {
                val latLng = LatLng(loc.latitude, loc.longitude)
                pathCollection.add(latLng)

            }
        }
        // 开始定位
        locationClient.startLocation()
    }

    fun drawPolyLineWithAMap(aMap: AMap) {
        if (pathCollection.size > 1) {
            val polylineOptions = PolylineOptions().apply {
                addAll(pathCollection)
                width(12f)
                color(Color.argb(255, 255, 0, 0))
                setDottedLine(true)
                useGradient(true)
            }
            aMap.addPolyline(polylineOptions)
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pathCollection.last(), 3f))
        }
    }

    fun startRandomLocToPathCollection(aMap: AMap) {
        handler.postDelayed(object : Runnable {
            override fun run() {
                // 随机生成全球范围内的经纬度
                val randomLatitude = -90.0 + Random.nextDouble() * 180.0 // 纬度范围：-90 到 90
                val randomLongitude = -180.0 + Random.nextDouble() * 360.0 // 经度范围：-180 到 180
                val randomLatLng = LatLng(randomLatitude, randomLongitude)
                pathCollection.add(randomLatLng)
                drawPolyLineWithAMap(aMap = aMap)
                handler.postDelayed(this, 5000) // 每5秒更新一次位置
            }
        }, 5000)
    }

    fun drawLineOnAMap(aMap: AMap) {
        val latLngs = listOf(
            LatLng(39.999391, 116.135972),
            LatLng(39.898323, 116.057694),
            LatLng(39.900430, 116.265061),
            LatLng(39.955192, 116.140092)
        )

        val polyline = aMap.addPolyline(
            PolylineOptions()
                .addAll(latLngs)
                .width(25f)
                .color(Color.argb(255, 1, 1, 1))
        )
    }

    fun drawACirleOnAMap(aMap: AMap) {
        val latLng = LatLng(39.984059, 116.307771)
        val circle = aMap.addCircle(
            CircleOptions()
                .center(latLng)
                .radius(1000.0)
                .fillColor(Color.argb(255, 1, 1, 1))
                .strokeColor(Color.argb(255, 1, 1, 1))
                .strokeWidth(15f)
        )
    }

    @Deprecated(message = "fucker fucker don't know why")
    fun queryAWeather() {
        // ref link: https://restapi.amap.com/v3/weather/weatherInfo?key=b4646339aeed54c67732cfd18bfa1e72&city=310100&extensions=all&output=json
        // https://console.amap.com/dev/key/app 使用web端的apikey
        val apiKey = "b4646339aeed54c67732cfd18bfa1e72"
        val cityCode = "440300"
        val url =
            "https://restapi.amap.com/v3/weather/weatherInfo?key=$apiKey&city=$cityCode&extensions=all&output=json"
        val request = Request.Builder()
            .url(url)
            .build()

        OkHttpClient().newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Toaster.show(e.message)
            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string()
                if (response.isSuccessful && responseBody != null) {
                    val weatherData = parseWeatherData(responseBody)
                    handler.post(
                        object : Runnable {
                            override fun run() {
                                Toaster.delayedShow("${weatherData.weather}", 5000)
                            }
                        }
                    )
                }
            }
        })
    }


    fun getAWetherData(context: Context, callback: (WeatherResponse?) -> Unit) {
        val CITY_CODE = "440300"
        val API_KEY = "b4646339aeed54c67732cfd18bfa1e72"
        val BASE_URL = "https://restapi.amap.com/v3/weather/weatherInfo"
        val url =
            "https://restapi.amap.com/v3/weather/weatherInfo?key=b4646339aeed54c67732cfd18bfa1e72&city=%E6%B7%B1%E5%9C%B3%E5%B8%82&extensions=all&output=json"
        val request = Request.Builder()
            .url(url)
            .build()

        OkHttpClient().newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback(null)
            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string()
                if (response.isSuccessful && responseBody != null) {
                    val gson = Gson()
                    val weatherResponse = gson.fromJson(responseBody, WeatherResponse::class.java)
                    callback(weatherResponse)
                } else {
                    callback(null)
                }
            }
        })
    }

    @Deprecated(message = "fucker fucker can not handle android")
    private fun parseWeatherData(json: String): WeatherData {
        // 使用 Gson 解析 JSON 数据
        val gson = Gson()
        val weatherResponse = gson.fromJson(json, WeatherResponse::class.java)
        // 提取第一个 Live 对象的天气信息
        val live = weatherResponse.lives?.firstOrNull() ?: return WeatherData("", "")
        return WeatherData(
            weather = live.weather,
            temperature = live.temperature
        )
    }

//    data class WeatherData(
//        val weather: String,
//        val temperature: String
//    )
//
//    data class Live()

    fun enableLocationFollow(aMap: AMap, value: Boolean) {
        var myLocationStyle: MyLocationStyle = MyLocationStyle()
        myLocationStyle.apply {
            interval(2000)
            // 永远显示在中间
            // todo: 这个方法不好
            if (value) {
//                myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW)
            } else {
//                myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
            }
            // 这个蓝点图标不能过大
            myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.car))
        }
        aMap.apply {
            myLocationStyle = myLocationStyle
            showIndoorMap(true)
            mapType = AMap.MAP_TYPE_NIGHT
            isTrafficEnabled = true
            setMapLanguage("en")
        }
    }


    // 离线下载内容没解决

    // 初始化 OfflineMapManager
//        offlineMapManager = OfflineMapManager(this, object : OfflineMapDownloadListener {
//            override fun onDownload(size: Int, current: Int, cityname: String?) {
//                // 下载进度回调
//                Toast.makeText(applicationContext, "下载进度回调", Toast.LENGTH_SHORT).show()
//            }
//
//            override fun onCheckUpdate(isUpdate: Boolean, provinceName: String?) {
//                // 检查更新回调
//                Toast.makeText(applicationContext, "检查更新回调", Toast.LENGTH_SHORT).show()
//
//            }
//
//            override fun onRemove(isSuccess: Boolean, provinceName: String?, cityName: String?) {
//                // 删除回调
//
//                applicationContext!!.apply {
//                    Toast.makeText(applicationContext, "删除回调", Toast.LENGTH_SHORT).show()
//                }
//
//            }
//        })
//        // 下载深圳的离线地图
//        downloadShenzhenOfflineMap()
//
//        startActivity(Intent(this, com.amap.api.maps.offlinemap.OfflineMapActivity::class.java))
//    private fun downloadShenzhenOfflineMap() {
//        // 获取所有省份的离线地图信息
//        val provinceList = offlineMapManager.getOfflineMapProvinceList()
//        for (province in provinceList) {
//            if (province.provinceName == "广东") {
//                // 获取广东省内的所有城市
//                val cityList = offlineMapManager.getOfflineMapCityList()
//                for (city in cityList) {
//                    if (city.city == "深圳") {
//                        // 下载深圳的离线地图
//                        offlineMapManager.downloadByCityName(city.adcode)
//                        break
//                    }
//                }
//                break
//            }
//        }
//    }

}